package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.AdminMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.pojo.Admin;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysLog;
import com.itheima.service.AdminService;
import com.itheima.service.AuthService;
import com.itheima.service.CreatCodeService;
import com.itheima.utils.*;
import com.itheima.vo.AdminVO;
import com.itheima.vo.AuthVO;
import com.itheima.vo.SysLogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;


@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AuthService authService;
    @Autowired
    private RedisTemplate redisTemplate;


    /*
    * 注册管理员
    * */
    @Override
    public void add(AuthVO authVO) {
        Admin admin = new Admin();
        admin.setUid(String.valueOf(idWorker.nextId()));
        admin.setUserName(authVO.getUserName());
        admin.setPassWord(authVO.getPassWord());
        admin.setGender("男".equals(authVO.getGender()) ? "1" : "2");
        admin.setAvatar(authVO.getAvatar());
        admin.setEmail(authVO.getEmail());
        admin.setBirthday(authVO.getBirthday());
        admin.setMobile(authVO.getMobile());
        admin.setValidCode(authVO.getValidCode());
        admin.setSummary(authVO.getSummary());
        admin.setCreateTime(DateUtils.getNowTime());
        admin.setUpdateTime(DateUtils.getNowTime());
        admin.setNickName(authVO.getNickName());
        admin.setQqNumber(authVO.getQqNumber());
        admin.setWeChat(authVO.getWeChat());
        admin.setOccupation(authVO.getOccupation());
        admin.setGithub(authVO.getGithub());
        admin.setGitee(authVO.getGitee());
        admin.setRoleUid(authVO.getRoleUid());
        admin.setPersonResume(authVO.getPersonResume());

        adminMapper.insertSelective(admin);

        //查找管理员的角色是否存在,不存在则添加角色
        Role role = roleMapper.selectByPrimaryKey(admin.getRoleUid());

        if (role == null) {
            role = new Role();
            role.setUid(String.valueOf(idWorker.nextId()));
            role.setRoleName(authVO.getRoleNames().toString());
            role.setCreateTime(DateUtils.getNowTime());
            role.setUpdateTime(DateUtils.getNowTime());
            role.setSummary(authVO.getSummary());

            roleMapper.insertSelective(role);
        }
    }

    /*
    * 删除管理员部分信息
    * */
    @Override
    public String delete(String adminUids) {
        //遍历查询管理员的uid
        Admin admin = adminMapper.selectByPrimaryKey(adminUids);
        admin.setUid(adminUids);
        admin.setStatus(0);
        adminMapper.updateByPrimaryKey(admin);
        return adminUids;
    }

    /*
     * 分配用户角色信息列表
     * */
    @Override
    public String assign(String adminUid) {
        //判断是否获取到值
        Admin admin = adminMapper.selectByPrimaryKey(adminUid);
        if (admin == null){
            return ResultUtils.result(500,MessageConstant.ADMIN_SELECT_FAIL);
        }
        //取出roleuid
        String roleUid = admin.getRoleUid();
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uid",roleUid);
        List<Role> roles = roleMapper.selectByExample(example);
        return ResultUtils.result(200,roles);
    }

    /*
    * 更新管理员基本信息
    * */
    @Override
    public String edit(Admin admin) {
        Admin admin1 = new Admin();
        String userName = admin.getUserName();
        //判断uid是否一样避免没必要的错误
        if (admin1.getUid().equals(admin.getUid())){
            admin.setCreateTime(admin1.getCreateTime());
            admin.setUpdateTime(DateUtils.getNowTime());
            admin.setLastLoginTime(DateUtils.getNowTime());
            adminMapper.updateByPrimaryKeySelective(admin);
            return ResultUtils.result(200,MessageConstant.ADMIN_EDIT_SUCCESS);
        }
        return ResultUtils.result(500,MessageConstant.ADMIN_EDIT_FAIL);
    }

    /*
    * 强退用户
    * */
    @Override
    public void forceLogout(String tokenList) {
        //调用logout方法来删除关于tokenlist进行强退
        authService.logout(tokenList);
    }

    /*
    * 获取管理员列表
    * */
    @Override
    public Page<Admin> getList(AdminVO adminVO) {
        if (adminVO!=null){
            //设置默认当前页
            if (adminVO.getCurrentPage() == null || "".equals(adminVO.getCurrentPage())) {
                adminVO.setCurrentPage(1);
            }
            //设置默认每页条数
            if (adminVO.getPageSize() == null || "".equals(adminVO.getPageSize())) {
               adminVO.setPageSize(10);
            }
        }else {
           adminVO  = new AdminVO();
           adminVO.setCurrentPage(1);
           adminVO.setPageSize(10);
        }
        Integer currentPage = adminVO.getCurrentPage();
        Integer pageSize = adminVO.getPageSize();
        PageHelper.startPage(currentPage,pageSize);
        Example example = createExample(adminVO);
        return (Page<Admin>)adminMapper.selectByExample(example);
    }

    /*
    * 重置用户密码
    * */
    @Override
    public String restPwd(String uid) {
        //获取用户的uid
        Admin admin = adminMapper.selectByPrimaryKey(uid);
        //把密码设置为空
        admin.setPassWord("");
        //更新设置的用户
        adminMapper.updateByPrimaryKeySelective(admin);
        return ResultUtils.result(200,MessageConstant.ADMIN_RESTPWD_SUCCESS);
    }

    /*
    * 更新管理员邮箱或手机号
    * */
    @Override
    public String updateEmail(String uid, String newInfo) {
        //获取用户uid
        Admin admin = adminMapper.selectByPrimaryKey(uid);
        if (newInfo.contains("@")){
            admin.setEmail(newInfo);
        }else{
            admin.setMobile(newInfo);
        }
        adminMapper.updateByPrimaryKeySelective(admin);
        return ResultUtils.result(200,MessageConstant.ADMIN_EDIT_FAIL);
    }

    /**
     * 获取在线管理员列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public List<Admin> getOnlineAdminList(Long currentPage, Long pageSize) {
        String prefix = "admin_*";
        List<Admin> list = new ArrayList<>();

        Set<String> keys = redisTemplate.keys(prefix);
        for (String key : keys) {
            Map<String,String> redisMap = redisTemplate.boundHashOps(key).entries();
            String uid = redisMap.get("uid");
            Admin admin = adminMapper.selectByPrimaryKey(uid);
            list.add(admin);
        }
        return list;
    }

    private Example createExample(AdminVO adminVO){
        Example example=new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if(adminVO!=null){
            // 用户名
            if(adminVO.getUserName()!=null && !"".equals(adminVO.getUserName())){
                criteria.andEqualTo("userName", adminVO.getUserName());
            }
            //uid
            if(adminVO.getUid()!=null && !"".equals(adminVO.getUid())){
                criteria.andEqualTo("uid", adminVO.getUid());
            }
        }
        return example;
    }


}
